<template>
    <view>
        <!-- pages/goodsDetail/index.wxml -->
        <!-- 头部 -->
        <navber id="head-navber" :navbarData="navbarData"></navber>

        <view class="detail">
            <view class="detail-photo">
                <swiper :indicator-dots="true" indicator-color="rgba(0,0,0,0.5)" indicator-active-color="rgba(255,255,255,1.00)" :autoplay="true" class="detail-photo-swiper">
                    <swiper-item v-for="(item, index) in goodsData.goods_photo" :key="item.key">
                        <image :src="item" class="detail-photo-swiper-img"></image>
                    </swiper-item>
                </swiper>
            </view>
            <view class="detail-vip">
                <view class="detail-vip-left">
                    <view class="detail-vip-left-img">
                        <image :src="imgUrl + '/imgs/award.png'"></image>
                    </view>
                    <view class="detail-vip-left-text">奖</view>
                    <view class="detail-vip-left-price">¥{{ goodsData.goods_return_money }}</view>
                </view>
                <view class="detail-vip-right">
                    <view class="detail-vip-right-text">最高可赚</view>
                    <view class="detail-vip-right-price">¥{{ goodsData.goods_return_money + goodsData.goods_top_money }}</view>
                    <view class="detail-vip-right-level" @tap="open_vip">
                        <view class="detail-vip-right-level-text">开通会员</view>
                        <view class="detail-vip-right-level-img">
                            <image :src="imgUrl + '/imgs/vip.png'"></image>
                        </view>
                    </view>
                </view>
            </view>
            <view class="detail-title">
                {{ goodsData.goods_title }}
            </view>
            <view class="detail-price">
                <view class="detail-price-layer">
                    <view class="detail-price-discount">¥{{ goodsData.goods_bazaar_price }}</view>
                    <view class="detail-price-primary">{{ goodsData.goods_original_price }}</view>
                    <view class="detail-price-number">销量：{{ goodsData.goods_sale }}</view>
                </view>
            </view>
            <view class="detail-text">
                {{ goodsData.goods_text }}
            </view>
            <view class="group-head" v-if="goodsData.order_number > 0">{{ goodsData.order_number }}人正在拼团，可直接参与</view>
            <view class="detail-group">
                <view class="group-list" v-for="(item, index) in goodsData.goods_group" :key="index">
                    <view class="detail-group-user">
                        <view class="detail-group-item" v-for="(i, index2) in item.items" :key="i.index2">
                            <view class="detail-group-item-img">
                                <image :src="i.head_img"></image>
                            </view>

                            <view class="detail-group-item-nickname">{{ i.nick_name }}</view>
                        </view>
                    </view>

                    <view class="detail-group-info">
                        <view class="detail-group-info-tip">
                            还差
                            <span class="number">{{ item.count - item.total }}人</span>
                            拼成
                        </view>
                        <view class="detail-group-info-time">剩余{{ goodsTime[index]['h'] + ':' + goodsTime[index]['m'] + ':' + goodsTime[index]['s'] }}</view>
                    </view>

                    <view class="goods-pt" @tap="set_pt_order($event, { groupid: index })" :data-groupid="index">参与拼团</view>
                </view>
            </view>
            <view class="detail-data">
                <view class="detail-data-search">
                    <view class="detail-data-search-img" @tap="toShare">
                        <image :src="imgUrl + '/imgs/goods/share.png'"></image>
                    </view>
                    <view class="detail-data-search-number">{{ goodsData.goods_share_count }}</view>
                </view>
                <view class="detail-data-collect">
                    <view class="detail-data-collect-layer">
                        <view class="detail-data-collect-img" @tap="upOrCollect($event, { type: '2' })" data-type="2">
                            <image :src="imgUrl + '/imgs/goods/' + (goodsData.is_up ? '' : 'not-') + 'goods_up.png'"></image>
                        </view>
                        <view :class="(goodsData.is_up ? '' : 'not-') + 'detail-data-collect-number'">{{ goodsData.goods_up_count }}</view>
                    </view>
                    <view class="detail-data-collect-layer detail-data-collect1" @tap="upOrCollect($event, { type: '1' })" data-type="1">
                        <view class="detail-data-collect-img">
                            <image :src="imgUrl + '/imgs/goods/' + (goodsData.is_collect ? '' : 'not-') + 'goods_then_collect.png'"></image>
                        </view>
                        <view :class="(goodsData.is_collect ? '' : 'not-') + 'detail-data-collect-number'">{{ goodsData.goods_collect_count }}</view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 详情 -->
        <view class="goodsDetail">
            <view class="goodsDetail-img">
                <view class="goodsDetail-img-title">商品详情</view>
                <view class="goodsDetail-img-list" v-if="is_show">
                    <image :src="item" mode="widthFix" v-for="(item, index) in goodsData.goods_detail" :key="index"></image>
                </view>
            </view>
        </view>

        <!-- 购买 -->
        <view class="orderSubmit">
            <view class="orderSubmit-cart" @tap="addCart">
                <view class="orderSubmit-cart-img">
                    <image :src="imgUrl + '/imgs/goods/cart.png'"></image>
                </view>
                <view class="orderSubmit-cart-text">加入购物车</view>
            </view>
            <view class="orderSubmit-but">
                <view class="orderSubmit-but-search">
                    <button class="orderSubmit-but-search-but" @tap="toShare">
                        <view class="orderSubmit-but-search-title">分享</view>
                        <view class="orderSubmit-but-search-price">奖￥{{ goodsData.goods_top_money }}</view>
                    </button>
                </view>
                <view class="orderSubmit-but-order" @tap="set_pt_order($event, { groupid: '' })" data-groupid="">
                    <view class="orderSubmit-but-order-title">发起拼团</view>
                    <view class="orderSubmit-but-order-price">省￥{{ buy_price }}</view>
                </view>
            </view>
        </view>
        <!-- 分享 -->
        <van-popup :show="shareShow" :closeable="true" position="bottom" custom-style="height: 374rpx" @close="onCloseShare">
            <view class="alignCenter shareTit">分享</view>
            <view class="alignCenter shareContent">
                <view class="flexCenter itemShare">
                    <button open-type="share"></button>
                    <image src="/static/assets/imgs/icon/weixin.png" class="wxLogoIcon"></image>
                    <view>分享好友</view>
                </view>
                <view class="flexCenter itemShare" @tap="getPoster">
                    <image src="/static/assets/imgs/icon/firends.png"></image>
                    <view>生成海报</view>
                </view>
            </view>
            <view class="shareTip">好物推荐，和大家一起分享你发现的好物</view>
        </van-popup>
        <!-- 海报图片 -->
        <van-popup
            :show="posterShow"
            :closeable="true"
            overlay-style="background:transparent"
            position="bottom"
            custom-style="height: 1078rpx"
            @close="onClosePoster"
            @click-overlay="onPoseterOverlay"
        >
            <view class="posterTit">保存到手机</view>
            <view v-if="posterImg">
                <view class="flexCenter posterContainer">
                    <image :src="posterImg"></image>
                </view>
                <view class="imgSaveBtn" @tap="onSavePoster">保存图片</view>
                <text class="flexCenter saveTip">保存图片到手机相册后，将图片分享到您的圈子</text>
            </view>
        </van-popup>
    </view>
</template>

<script>
import navber from '@/components/navber/index';
// pages/goodsDetail/index.js
const Config = require('../../../config/index.js');

const Api = require('../../../api/index.js');

const app = getApp();
export default {
    components: {
        navber,
    },
    data() {
        return {
            navbarData: {
                title: '商品详情',
                //顶部标题
                is_show_bottom: true,
                //显示背景图
                bac_img: '/assets/imgs/navbar/navbar_bg1' //显示背景图片
            },

            //导航栏
            imgUrl: Config.imgUrl,

            //图片url
            goods_id: 0,

            //商品id
            group: '',

            //是否是拼团商品
            goodsData: [],

            //数据
            goodsTime: {},

            //数据
            count_down: false,

            is_show: false,

            //是否显示详情
            buy_price: 0,

            //
            is_show_page: false,

            buy_price: 0,

            //
            shareShow: false,

            posterShow: false,
            posterImg: '',

            i: {
                index2: '',
                head_img: '',
                nick_name: ''
            }
        };
    },
    onLoad: function (option) {
        let goods_id = option.id;

        if (option.scene) {
            //通过海报进入
            let sceneData = decodeURIComponent(option.scene);

            if (sceneData.indexOf('_') > 0) {
                let newData = sceneData.split('_');
                goods_id = newData[0];
            }
        }

        let group = '';

        if (option.group) {
            group = 'group';
        } // console.log(goods_id);

        if (goods_id == null || goods_id == undefined || goods_id == '') {
            uni.showToast({
                title: '商品不存在',
                icon: 'error',
                duration: 2000
            });
            setTimeout(function () {
                uni.navigateBack();
            }, 2000);
        } else {
            this.setData({
                goods_id: goods_id,
                group: group
            });
            this.getDetail();
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: this.goodsData.goods_title,
            path: '/pages/goodsDetail/index?id=' + this.goodsData.id + '&code=' + app.globalData.popularize_code,
            imageUrl: this.goodsData.goods_img,
            success: function (res) {
                // 转发成功之后的回调
                if (res.errMsg == 'shareAppMessage:ok') {
                    var json = {
                        goods_id: this.goodsData.id
                    };
                    Api.shareAdd(json).then({});
                }
            }
        };
    },
    onPullDownRefresh: function () {
        this.getDetail();
        uni.stopPullDownRefresh();
    },
    onUnload() {
        this.setData({
            is_show_page: false
        });
    },
    onReachBottom: function () {
        this.setData({
            is_show: true
        }); // 显示加载图标
    },
    methods: {
        //弹出分享选择
        toShare: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            this.setData({
                shareShow: true
            });
        },

        getPoster: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            var that = this;
            this.setData({
                posterShow: true
            });
            var json = {
                goods_id: this.goods_id,
                code: app.globalData.popularize_code,
                path: 'pages/goodsDetail/index'
            };
            Api.createQRcode(json).then((res) => {
                if (res.code == 1) {
                    that.setData({
                        posterImg: res.data
                    });
                }
            });
        },

        //保存图片
        onSavePoster: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            let that = this;
            uni.getSetting({
                success: function (res) {
                    if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting['scope.writePhotosAlbum'] != true) {
                        uni.showModal({
                            title: '请授权保存到相册',
                            content: '需要保存到相册权限，请确认授权',
                            success: function (res) {
                                if (res.cancel) {
                                    uni.showToast({
                                        title: '取消授权',
                                        icon: 'none',
                                        duration: 1000
                                    });
                                } else if (res.confirm) {
                                    uni.openSetting({
                                        success: function (dataAu) {
                                            if (dataAu.authSetting['scope.writePhotosAlbum'] == true) {
                                                uni.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 1000
                                                });
                                                that.authSaveImg();
                                            } else {
                                                uni.showToast({
                                                    title: '授权失败',
                                                    icon: 'none',
                                                    duration: 1000
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    } else if (res.authSetting['scope.writePhotosAlbum'] == undefined) {
                        that.authSaveImg();
                    } else {
                        that.authSaveImg();
                    }
                },

                fail(res) {}
            });
        },

        //授权
        authSaveImg: function () {
            let that = this;
            uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success: function (res) {
                    let imgurl = that.posterImg;
                    uni.downloadFile({
                        url: imgurl,
                        success: function (res) {
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function (res) {
                                    uni.showToast({
                                        title: '保存成功'
                                    });
                                    that.shareSuceese();
                                }
                            });
                        }
                    });
                },

                fail(res) {
                    console.log(res);
                    uni.showToast({
                        title: '授权失败',
                        icon: 'none'
                    });
                }
            });
        },

        //关闭分享
        onCloseShare: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            this.setData({
                shareShow: false
            });
        },

        //关闭海报
        onClosePoster: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            this.setData({
                posterShow: false
            });
        },

        //点击遮罩层
        onPoseterOverlay: function (e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            this.setData({
                shareShow: false
            });
        },

        getDetail() {
            //详情接口
            var json = {
                goods_id: this.goods_id,
                group: this.group
            };
            Api.goodsDetail(json).then((res) => {
                if (res.code == 1) {
                    if (res.data.is_group_goods == 1) {
                        var price = res.data.goods_bazaar_price - res.data.sell_price;
                    } else {
                        var price = res.data.goods_bazaar_price - res.data.goods_original_price;
                    }

                    let goods_group = res.data.goods_group;
                    let goods_group_tem = {};
                    var is_page = false;

                    for (let key in goods_group) {
                        goods_group_tem[key] = goods_group[key].time_arr;
                        is_page = true;
                    }

                    this.setData({
                        goodsTime: goods_group_tem,
                        goodsData: res.data,
                        buy_price: price.toFixed(2),
                        is_show_page: is_page
                    });
                    this.countDown();
                } else {
                    uni.showToast({
                        title: '商品不存在',
                        icon: 'error',
                        duration: 2000
                    });
                    setTimeout(function () {
                        uni.navigateBack();
                    }, 2000);
                } // wx.stopPullDownRefresh();
            });
        },

        open_vip(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //开通vip
            uni.navigateTo({
                url: '/pages/user/vip/index'
            });
        },

        isDetailShow() {
            //是否显示详情
        },

        upOrCollect(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //点赞收藏
            var json = {
                goods_id: this.goods_id,
                type: e.currentTarget.dataset.type
            };
            Api.upOrCollect(json).then((res) => {
                if (res.code == 1) {
                    this.getDetail();
                }
            });
        },

        addCart(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //加入购物车
            var json = {
                goods_id: this.goodsData.id
            };
            Api.goodsAddCart(json).then((res) => {
                if (res.code == 1) {
                    uni.showToast({
                        title: '加入成功',
                        icon: 'success',
                        duration: 2000
                    });
                }
            });
        },

        set_pt_order(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //设置拼团订单
            var goods_id = this.goodsData.id;
            let group_id = e.currentTarget.dataset.groupid;
            uni.navigateTo({
                url: '/pages/goodsDetail/order/index?goods_id=' + goods_id + '&type=pt_order&group_id=' + group_id
            });
        },

        // 倒计时
        countDown() {
            let that = this;
            var goods_time_temp = that.goodsTime;
            let goods_timep_tem = {};

            for (let key in goods_time_temp) {
                goods_timep_tem[key] = that.timeDec(goods_time_temp[key]);
            }

            this.setData({
                goodsTime: goods_timep_tem
            });

            if (this.is_show_page) {
                setTimeout(that.countDown, 1000);
            }
        },

        //时间自减少
        timeDec(time_arr) {
            var h = parseInt(time_arr['h']);
            var m = parseInt(time_arr['m']);
            var s = parseInt(time_arr['s']);
            s -= 1;

            if (s == 0) {
                m -= 1;
                s = 59;

                if (m == 0) {
                    h -= 1;
                    m = 59;

                    if (h == 0) {
                        return {
                            h: '00',
                            m: '00',
                            s: '00'
                        };
                    }
                }
            }

            h = this.timeFormat(h);
            m = this.timeFormat(m);
            s = this.timeFormat(s);
            return {
                h: h,
                m: m,
                s: s
            };
        },

        //小于10的格式化函数（2变成02）
        timeFormat(param) {
            return param < 10 ? '0' + param : param;
        },

        //小于0的格式化函数（不会出现负数）
        timeFormin(param) {
            return param < 0 ? 0 : param;
        }
    }
};
</script>
<style>
@import './index.css';
</style>
